package com.wujian.love.controller;

import com.wujian.love.redis.RedisLock;
import com.wujian.love.redis.RedisService;
import com.wujian.love.utils.CodeGeneratorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.util.NamedThreadFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: RedisDemoController
 * @Description: 分布式锁测试
 * @Author: wuj
 * @Date: 2021-01-12 09:52
 **/
@RestController
@RequestMapping("/redis")
@Slf4j
public class RedisDemoController {


    @Autowired
    RedisLock redisLock;


    @Autowired
    private RedisService redisService;

    int count = 0;

    @RequestMapping("/index")
    public String index() throws InterruptedException {

        int clientcount =1000;
        CountDownLatch countDownLatch = new CountDownLatch(clientcount);

        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                10,20,600L, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(clientcount),new NamedThreadFactory("reids-test"));
        // 设置拒绝策略，默认为 AbortPolicy
        threadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());

        long start = System.currentTimeMillis();
        for (int i = 0;i<clientcount;i++){
            threadPool.execute(() -> {
                String id = CodeGeneratorUtils.nextId();
                long threadId = Thread.currentThread().getId();
                redisService.set("线程号",threadId);
                System.out.println(threadId);
                try {
                    redisLock.lock(id);
                    count++;
                }finally {
                    redisLock.unlock(id);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        long end = System.currentTimeMillis();
        log.info("执行线程数:{},总耗时:{},count数为:{}",clientcount,end-start,count);
        return "Hello";
    }





}
